<template>
  <div>
    <el-container>
      <el-container class="rightMain">
        <bs-main class="bsMain">
          <manage-condition slot="header"></manage-condition>
          <list
            ref="roletable"
            class="left"
            :list-data="tabledata"
            :has-select="false"
            :list-cols="listCols"
            :action-opts="actionOpts"
            :init-cols-props.sync="initColsProps"
            height="calc(100vh - 220px)"
            :highlight="true"
            :table-tag="tableName"
            :init-headmune-flag="initHeadmuneFlag"
            @sort="handleSort"
            @filter="handleFilter"
            @cunrrent-change="handleCurrentChange"
            @init-table="initTable"
          ></list>
          <pagination
            slot="footer"
            :total="pageData.total"
            :page="pageData.page"
            :limit="pageData.limit"
            @pagination="requestRoleList"
          ></pagination>
        </bs-main>
        <actor-edit-dialog></actor-edit-dialog>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import List from '@/components/List'
import Pagination from '@/components/Pagination'
import ManageCondition from './components/ManageCondition'
import ActorEditDialog from './components/ActorEditDialog'

export default {
  components: {
    List,
    ManageCondition,
    ActorEditDialog,
    Pagination,
  },
  data() {
    const headerContextMenus = {
      width: '120px',
      items: ['sortUp', 'sortDown', 'line', 'cols', 'line'],
    }
    return {
      pageData: {
        total: 0,
        page: 1,
        limit: 15,
      },
      initHeadmuneFlag: false,
      tabledata: [],
      permissionGroup: [],
      currentRow: null,
      showContextMenu: false,
      defaultCheckedKeys: [],
      contextMenuData: [],
      tableName: 'roletable',
      listCols: [
        {
          label: this.$t('角色名称'),
          prop: 'name',
          sortable: false,
          align: 'left',
          width: 180,
        },
        {
          label: this.$t('授予权限'),
          prop: 'permission',
          sortable: false,
          align: 'left',
        },
      ],
      initColsProps: ['name', 'permission'],
      actionOpts: {
        show: false,
      },
    }
  },
  mounted() {
    this.$nextTick(function () {
      this.requestPermissionGroup()
    })
  },
  methods: {
    initTable(config) {
      this.initHeadmuneFlag = true
    },
    handleSort(sortInfo) {
      switch (sortInfo.prop) {
        case 'name':
          break
        case 'permission':
          break
        default:
          break
      }
      console.log('sortInfo----', sortInfo)
    },
    //变量权限列数组 拼接权限字符串
    formatAuthories(row, column) {
      var authArray = row[column.property]
      var authStr = ''
      if (!authArray) {
        return
      }
      authArray.forEach((item) => {
        authStr = authStr + ',' + item.resourceName
      })
      return authStr
    },

    handleFilter(filterInfo) {
      console.log('filterInfo----', filterInfo)
    },
    //选中行变更
    handleCurrentChange(val) {
      this.$eventBus.$emit('selectRow', val)
      this.currentRow = val
    },
    refreshActorlist(val) {
      let result = this.refreshRoleList(val)
    },
    //获取所有权限数组
    requestPermissionGroup() {
      let params = {}
      this.$store
        .dispatch('system/loadPermissionResource', params)
        .then((res) => {
          this.permissionGroup = res
          this.$eventBus.$emit('updatePermissionList', this.permissionGroup)
          this.requestRoleList()
        })
    },
    //获取角色列表信息
    requestRoleList(current) {
      if (current) {
        this.pageData = {
          ...this.pageData,
          ...current,
        }
      }
      let param = {
        current: this.pageData.page,
        size: this.pageData.limit,
      }
      this.$store.dispatch('system/loadroleList', param).then((res) => {
        if (res) {
          this.tabledata = res.records  ? res.records : []
          this.pageData.total = res.total ? Number(res.total) : 0
          this.tabledata.forEach((element) => {
            //根据id组 获取权限组
            if (element.permissionCodeList) {
              element.authed = filterPermission(
                element.permissionCodeList,
                this.permissionGroup
              )
              element.unauthed = removPermission(
                element.permissionCodeList,
                this.permissionGroup
              )
            }else{
              element.authed =[]
              element.unauthed =this.permissionGroup
            }
            console.log('row element = ', element)
          })
        }else{
        }
      })
    },
    //刷新角色列表信息
    refreshRoleList(tip) {
      let param = {
        current: this.pageData.page,
        size: this.pageData.limit,
      }
      this.$store.dispatch('system/loadroleList', param).then((res) => {
        if (res) {
          if(tip){
            this.$message.success(this.$t('刷新成功'))
          }
          this.tabledata = res.records ? res.records : []
          this.pageData.total = res.total ? Number(res.total) : 0
          this.tabledata.forEach((element) => {
            //根据id组 获取权限组
            if (element.permissionCodeList) {
              element.authed = filterPermission(
                element.permissionCodeList,
                this.permissionGroup
              )
              element.unauthed = removPermission(
                element.permissionCodeList,
                this.permissionGroup
              )
            }else{
              element.authed =[]
              element.unauthed =this.permissionGroup
            }
            console.log('row element = ', element)
          })
        }else{
        }
      })
    },
  },
  created() {
    this.$eventBus.$on('refreshActorlist', this.refreshActorlist)
  },
  beforeDestroy() {
    this.$eventBus.$off('refreshActorlist')
  },
}
//根据权限id数组过滤已有权限
function filterPermission(permissionids, permissionGroup) {
  var authed = []
  permissionids.forEach((ele) => {
    var inGroup = permissionGroup.find((x) => x.code === ele)
    inGroup ? authed.push(inGroup) : ''
  })
  return authed
}
//根据权限id数组过滤未授权权限
function removPermission(permissionids, permissionGroup) {
  var arr1 = []
  var arr2 = []
  arr1 = arr1.concat(permissionGroup)
  arr2 = arr2.concat(permissionids)
  for (let i = arr1.length - 1; i >= 0; i--) {
    for (let j = arr2.length - 1; j >= 0; j--) {
      if (arr1[i].code == arr2[j]) {
        arr1.splice(i, 1)
        break
      }
    }
  }
  return arr1
}
</script>